<?php
/**
 * CK 开发框架
 * User: Clake
 * Date: 15/6/22
 * Time: 02:43
 */

namespace CK\Util;

use CK\Core\Component;
use CK\Core\Router;
use CK\Util\IO\Directory;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class Log extends Component{

    private $_conf = [
        //默认日志目录
        'path'=>APP_LOG_PATH
    ];

    private $_logs = [];

    public function __construct() {

    }

    public function access($msg,$extra=[]) {
        $this->createLogger('access')->addInfo($msg,$extra);
    }

    public function error($msg,$extra=[]) {
        $this->createLogger('error')->addInfo($msg,$extra);
    }

    public function warning($msg,$extra=[]) {
        $this->createLogger('warning')->addInfo($msg,$extra);
    }

    /**
     * 创建一个日志记录器
     * @param string $name 日志名称
     * @return Logger
     */
    public function createLogger($name) {
        if (isset($this->_logs[$name])) {
            return $this->_logs[$name];
        } else {
            $router = Router::inst();
            $log_path = $router->getRouterParam('module').'/'.$router->getRouterParam('controller').
                '/'.$name.'_'.date('Y_m_d').'.log';
            $log_path = strtolower($log_path);
            $dir = dirname(APP_LOG_PATH.$log_path);
            if (!Directory::Exists($dir)) {
                Directory::Create($dir);
            }
            $log = new Logger($name);
            $log->pushHandler(new StreamHandler(APP_LOG_PATH.$log_path,Logger::INFO));
            $this->_logs[$name] = $log;
            return $log;
        }

    }
}